// pages/lishida/lishida.js
Page({
  data: {
    questionDetail: {}, // 存储题目信息
    index: 0, // 当前题目下标
    userAnswers: {}, // 存储用户选择的答案
    correctAnswers: {}, // 存储正确答案
    answeredQuestions: [], // 存储已答题目的 ID
    showSelected: false, // 控制是否显示选中状态
    isAnswered: false,
  },


  onLoad(options) {
    //console.log('接收到的参数:', options);  

    const {
      paperId,
      quId,
      index
    } = options;
    this.setData({
      index: parseInt(index),
    });

    this.paperId = paperId;
    this.quId = quId;

    this.fetchQuestionDetail(this.paperId, this.quId);
  },

  onShow() {
    this.fetchQuestionDetail(this.paperId, this.quId);
  },

  fetchQuestionDetail(paperId, quId) {
    const that = this;
    // 重置显示答案状态
    that.setData({
      showCorrectAnswer: false // 重置为 false
    });
    const app = getApp();
    wx.request({
      method: 'POST',
      url: `${app.globalData.baseUrl}/paper/qu-detail`,
      header: {
        'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzI1NTg3MTcsInVzZXJJZCI6MTgyNzk5OTgyMTczMTA5ODYyNn0.SxS7ENOxgqgIh8AAn_Sw84R_zvFA99_khzsVNCDShLk'
      },
      data: {
        paperId: paperId,
        quId: quId
      },
      success(res) {
        if (res.statusCode === 200 && res.data.code === 1) {
          const questionData = res.data.data;
          that.setData({
            questionDetail: questionData // 存储题目信息
          });

          const {
            answered,
            answerList
          } = questionData;
          // 处理用户答案  
          let selectedAnswerId = null;
          if (answered) {
            for (const answer of answerList) {
              if (answer.checked) {
                selectedAnswerId = answer.abc; // 获取用户选择的答案  
                break;
              }
            }
          }

          // 更新数据  
          that.setData({
            userAnswers: {
              ...that.data.userAnswers,
              [quId]: selectedAnswerId // 更新用户答案  
            },
            correctAnswers: {
              ...that.data.correctAnswers,
              [quId]: answerList.find(answer => answer.isRight) // 存储正确答案  
            },
            showSelected: answered, // 标记是否显示选中状态  
            isAnswered: answered
          });
        } else {
          console.error('获取题目详情失败:', res.data);
        }
      },
      fail(err) {
        console.error('请求失败:', err);
      }
    });
  },

  onPrevQuestion() {
    const newIndex = this.data.index - 1;
    const questions = wx.getStorageSync(`papers`);
    if (newIndex >= 0 && questions[newIndex]) {
      const paperId = questions[newIndex].paperId;
      const quId = questions[newIndex].quId;
      this.setData({
        index: newIndex,
        showSelected: true
      });

      this.fetchQuestionDetail(paperId, quId);
    } else {
      wx.showToast({
        title: '已经是第一题了',
        icon: 'error'
      });
    }
  },

  onNextQuestion() {
    const newIndex = this.data.index + 1;
    const questions = wx.getStorageSync(`papers`);

    if (newIndex < questions.length) {
      const paperId = questions[newIndex].paperId;
      const quId = questions[newIndex].quId;
      this.setData({
        index: newIndex,
        showSelected: true
      });
      this.fetchQuestionDetail(paperId, quId);

    } else {
      wx.showToast({
        title: '没有下一题了',
        icon: 'none'
      });
    }
  },

  onOptionSelect(event) {
    const userAnswerValue = event.detail.value; // 获取用户选择的答案  
    const {
      quId,
      paperId,
      answerList
    } = this.data.questionDetail; // 获取当前题目的 quId 和 paperId  

    //检查是否选过了
    if (this.data.isAnswered) {
      wx.showToast({
        title: '此题以答',
        icon: 'error'
      })
      return; //如果已经答过，终止函数
    }

    // 存储用户答案  
    this.setData({
      userAnswers: {
        ...this.data.userAnswers,
        [quId]: userAnswerValue // 使用 quId 作为键  
      },
      isAnswered: true, //固定已经答过的题目
      showSelected: true // 用户选择后不再显示选中状态  
    });

    // 找到用户选择的答案  
    const selectedAnswer = answerList.find(item => item.abc === userAnswerValue);

    // 获取选中答案的 ID  
    const selectedAnswerId = selectedAnswer ? selectedAnswer.id : null;
   // const selectedImageText = answerList[index] ? answerList[index].image : null; 
    // 找到正确答案  
    const correctAnswer = answerList.find(item => item.isRight === true);
    // 更新状态  
    this.setData({
      correctAnswers: {
        ...this.data.correctAnswers,
        [quId]: correctAnswer ? correctAnswer : null // 存储正确答案  

      },
    });
    const app = getApp();
    // 发送请求判断答案  
    wx.request({
      method: 'POST',
      url: `${app.globalData.baseUrl}/paper/fill-answer`,
      header: {
        'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzI1NTg3MTcsInVzZXJJZCI6MTgyNzk5OTgyMTczMTA5ODYyNn0.SxS7ENOxgqgIh8AAn_Sw84R_zvFA99_khzsVNCDShLk'
      },
      data: {
        answers: [selectedAnswerId], // 将选中答案的 ID 放入数组中  
        paperId: paperId,
        quId: quId
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 1) {
          console.log('答案判断成功');
        } else {
          console.error('获取答案判断失败:', res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },

  renderAnswerrs() {
    const {
      answerList,
      quId,
      userAnswers
    } = this.data.questionDetail;
    return answerList.map(item => {
      return {
        ...item,
        checked: userAnswers[quId] == item.abc
      }
    })
  },

  onViewAnswer() {
    const {
      quId,
      paperId,
      answerList,
      index
    } = this.data.questionDetail; // 获取当前题目的 quId 和 paperId 
    //检查是否选过了
    if (this.data.isAnswered) {
      this.setData({
        showCorrectAnswer: true, // 如果已答，直接显示正确答案  
      });
      return; //如果已经答过，终止函数
    }

    // 存储用户答案  
    this.setData({
      isAnswered: true, //固定已经答过的题目
      showSelected: true // 用户选择后不再显示选中状态  

    });

    // 获取选中答案的 ID  
    const selectedAnswerId = answerList[index] ? answerList[index].id : null; // 根据 index 获取答案 ID 
    const app = getApp();
    // 发送请求判断答案  
    wx.request({
      method: 'POST',
      url: `${app.globalData.baseUrl}/paper/fill-answer`,
      header: {
        'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzI1NTg3MTcsInVzZXJJZCI6MTgyNzk5OTgyMTczMTA5ODYyNn0.SxS7ENOxgqgIh8AAn_Sw84R_zvFA99_khzsVNCDShLk'
      },
      data: {
        answers: [selectedAnswerId], // 将选中答案的 ID 放入数组中  
        paperId: paperId,
        quId: quId
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 1) {
          console.log('答案判断成功');
        } else {
          console.error('获取答案判断失败:', res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });

    this.setData({
      showCorrectAnswer: true,
    });
  },

  // 返回到上一页  
  onGoBack() {
    wx.navigateBack({});
  },

  onGoackhome() {
    wx.showModal({
      title: '提示',
      content: '是否要退出答题',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: `/pages/home/home`
          });
          console.log('用户点击确定');
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      },
    });
  },
});